import React, {
  memo,
  useCallback,
  useEffect,
  useState,
  useImperativeHandle,
} from "react";
import { connect } from "react-redux";
import PubSub from "pubsub-js";

import style from "./index.css";
import {
  setCurrentsong,
  setCurrentDetailAct,
  setCurrentSongNewAct,
} from "@/redux/actions";

const SongItem = ({ song, playsongs, currentSongDetail }) => {
  const playsongsFun = () => {
    playsongs();
  };
  return (
    <div
      className={[
        style.songitem,
        currentSongDetail.id === song.id ? style.songAvtive : "",
      ].join(" ")}
      onClick={playsongsFun}
    >
      {currentSongDetail.id === song.id ? (
        <img
          src={require("./Icon/itemPlay.svg").default}
          alt="itemPlay"
          className={style.itemplay}
        />
      ) : null}
      <div className={style.songname}>{song.name}</div>
      <div className={style.songAuthor}>
        {song.ar
          ? song.ar.map((arname) => <div key={arname.id}>{arname.name}</div>)
          : null}
      </div>
      <div>{(song.id / 1000 / 60 / 60 / 60).toFixed(2)}</div>
      <img
        src={require("./Icon/lianjie.svg").default}
        alt="链接"
        className={style.ljIcon}
      />
    </div>
  );
};

const LrcContainer = ({
  sendlrcDetail,
  currentTime,
  playing,
  listTopRef,
  lrcTotalArr,
  lrcNamesArr,
  lrcTimesArr,
}) => {
  const [lrcNames, setLrcnames] = useState([]);
  const [lrcTimes, setLrcTimes] = useState([]);
  // const [lrcArrTotal, setLrcArrTotal] = useState([])
  const [currentIndex, setCurrentIndex] = useState(0);

  console.log(sendlrcDetail, "lrcNames LrcContainer");
  console.log(sendlrcDetail, "lrcTimes LrcContainer");
  // useEffect(() => {
  //   let lyric = sendlrcDetail.lyric;
  //   let lrcTimesArr = [];
  //   let lrcNamesArr = [];
  //   let lrcTotalArr = []
  //   if (!lyric) {
  //     return
  //   }
  //   lyric.split("\n").forEach((item) => {
  //     let reg = new RegExp(/\[(\S*)\]/);

  //     let strName = String(item.replace(reg, ""));
  //     lrcNamesArr.push(strName);

  //     let matchResultArr = item.match(reg);
  //     let str = matchResultArr ? matchResultArr[1] : "";

  //     let strNameRes = ''
  //     if (strName) {
  //       let strNameResArr = str.replace('.', ":").split(':')
  //       let min = parseInt(strNameResArr[0])
  //       let second = parseInt(strNameResArr[1])
  //       let msecond = parseInt(strNameResArr[2])
  //       strNameRes = msecond + second * 1000 + min * 1000 * 60
  //     }

  //     lrcTimesArr.push(strNameRes);
  //     lrcTotalArr.push({lrcNames: strName, lrcTimes: strNameRes})
  //   })

  //   console.log(lrcTotalArr, 'lrcTotalArr LrcContainer');

  //   setLrcnames(lrcNamesArr);
  //   setLrcTimes(lrcTimesArr);
  //   setLrcArrTotal(lrcTotalArr)

  // }, [sendlrcDetail]);

  // useEffect(() => {
  // [1,2,3,4,5,6,7]
  // time = 0 -> 找到第一句歌词，设置active样式， 并且设置一个定时器，时间为times[1] - times[0]
  // time = 1 => 找到第二句歌词，设置active样式， 并且设置一个定时器，时间为times[1] - times[0]

  // 70 -> 找到所在的歌词下标，设置active样式， 并且设置一个定时器，时间为times[index] - times[index-1]
  console.log(currentTime, 'currentTime setCurrentlyric');

  // if (playing) {
  console.log('setLRcNextTime player');
  // setLRcNextTime(currentIndex)
  // }else{
  //   console.log('暂停');
  // setLRcNextTime(currentTime)
  // }

  // }, [currentTime, currentIndex])

  // const setLRcNextTime = useCallback((index) => {
  //   console.log(lrcNames.length, 'lrcNames.length LrcContainer')
  //   console.log(index, 'index LrcContainer')
  //   if(!lrcNames.length){
  //     return
  //   }
  //   // 找下标
  //   let resultindex
  //   for(let i in lrcTimes){
  //     let ct = parseInt(currentTime * 1000)
  //     if (ct >= lrcTimes[i] && ct < lrcTimes[i+1]) {
  //       resultindex = i
  //       console.log(resultindex, '记住这个i LrcContainer');
  //     }
  //   }

  //   console.log('设置' + lrcNames[index] + '的样式 LrcContainer');
  //   if (index > 15) {
  //     return
  //   }
  //   setTimeout(() => {
  //     setLRcNextTime(index + 1)
  //   }, lrcTimes[index + 1] - lrcTimes[index]);
  // }, [lrcNames])

  useEffect(() => {
    PubSub.subscribe("startChangeLryic", startChangeLryic);
    // setLrcTimes()
    // setLrcnames()
    // if (lrcArrTotal.length) {
    //   console.log('useeffect,startChangeLryic LrcContainer')
    // }else{
    //   console.log('空的 lrcArrTotal LrcContainer')
    // }
  }, []);

  const startChangeLryic = useCallback(
    (nodata, time) => {
      console.log(
        "LrcContainer",
        nodata,
        time,
        lrcNamesArr,
        lrcTimesArr
      );
      if (lrcNamesArr && lrcTimesArr && lrcTotalArr) {
        let lrcNames = lrcNamesArr;
        let lrcTimes = lrcTimesArr;
        console.log(lrcNames, ` lrcTimesArr lrcTotalArr LrcContainer`);
        console.log(lrcTimes, ` lrcTimesArr lrcTotalArr LrcContainer`);

        // 找下标
        for (let i in lrcTimes) {
          let ct = parseInt(time * 1000);
          debugger
          if (ct >= lrcTimes[i] && ct < lrcTimes[i + 1]) {
            let resultindex = parseInt(i);
            console.log(resultindex, "记住这个i LrcContainer");

            console.log("设置" + lrcNames[resultindex] + "的样式 LrcContainer");

            if (!lrcNames[resultindex]) {
              return;
            }
            if (resultindex > 3) {
              return;
            }
            let setTime = lrcTimes[resultindex + 1] - lrcTimes[resultindex];
            console.log(setTime, "settime");
            // setTimeout(() => {
            //   startChangeLryic(lrcTimes[resultindex + 1])
            // }, setTime);
            return
          } else {
            console.log(ct, " ct not found LrcContainer");
          }
        }
        console.log(
          "startChangeLryic useCallback lrcTimes LrcContainer",
          nodata,
          time,
          lrcTimes
        );
      }
    },
    [lrcNamesArr, lrcTimesArr, lrcTotalArr]
  );

  return (
    <div className={style.lrcNamesItem}>
      {console.log(lrcTotalArr, "lrcArrTotal")}
      {lrcNamesArr
        ? lrcNamesArr.map((item, index) => (
            <div className={index == 3 ? style.nameActive : null}>{item}</div>
          ))
        : null}
    </div>
  );
};

const PlayerListTop = ({
  songsList = [],
  currentSongDetail,
  playSongGlobal,
  sendlrcDetail,
  currentTime,
  listTopRef,
  lrcTotalArr,
  lrcTimesArr,
  lrcNamesArr,
}) => {
  const [clickTime, setClickTime] = useState("done");
  console.log(sendlrcDetail, 'sendlrcDetail PlayerListTop1')

  const playsongs = useCallback(
    async (song) => {
      console.log("playsongs", song);
      // 添加点击次数节流
      if (clickTime != "done") {
        console.log("重复点击!");
        return;
      }
      setClickTime("doing");
      console.log(Date.now(), "playerlisttop");
      setClickTime("done");
      playSongGlobal(song);
    },
    [songsList, clickTime]
  );

  return (
    <div className={style.containter}>
      <div className={style.listContent}>
        <div className={style.listHeader}>
          <div className={style.listTitle}>播放列表({songsList.length})</div>
          <div className={style.listStar}>
            <img src={require("./Icon/star.svg").default} alt="收藏" />
            收藏全部
          </div>
          <div className={style.listStar}>
            <img src={require("./Icon/clear.svg").default} alt="清除" />
            清除
          </div>
        </div>
        <div className={style.listBody}>
          {songsList.length > 0
            ? songsList.map((song, index) => (
                <SongItem
                  currentSongDetail={currentSongDetail}
                  song={song}
                  key={song.al.id}
                  playsongs={() => playsongs(song)}
                  index={index}
                />
              ))
            : null}
        </div>
      </div>
      <div className={style.lrcContent}>
        <div className={style.lrcHeader}>{currentSongDetail.name}</div>
        <div className={style.lrcBody}>
          {sendlrcDetail ? (
            <LrcContainer
              sendlrcDetail={sendlrcDetail}
              currentTime={currentTime}
              listTopRef={listTopRef}
              lrcTotalArr={lrcTotalArr}
              lrcTimesArr={lrcTimesArr}
              lrcNamesArr={lrcNamesArr}
            />
          ) : (
            // <div>{sendlrcDetail.lyric}</div>
            <div className={style.noLrc}>纯音乐，无歌词</div>
          )}
        </div>
      </div>
    </div>
  );
};

const mstate = (state) => {
  console.log(state, 'state');
  return {
    currentSongDetail: state.currentDoingInfo.currentSongDetail,
    sendlrcDetail: state.currentDoingInfo.sendlrcDetail,
    currentTime: state.playerChangeData.currentTime,
    lrcTotalArr: state.currentDoingInfo.lrcArrTotal.lrcTotalArr,
    lrcTimesArr: state.currentDoingInfo.lrcArrTotal.lrcTimesArr,
    lrcNamesArr: state.currentDoingInfo.lrcArrTotal.lrcNamesArr,
  };
};
const mdispatch = (dispatch) => {
  return {
    setCurrentSong: (data) => {
      dispatch(setCurrentsong(data));
    },
    setCurrentSongDetail: (data) => {
      dispatch(setCurrentDetailAct(data));
    },
    setNewSongs: (data) => {
      dispatch(setCurrentSongNewAct(data));
    },
  };
};
export default connect(mstate, mdispatch)(PlayerListTop);
